<template>
  <div>
    <el-form :inline="true" :model="pageParams">
      <el-form-item label="任务名称">
        <el-input clearable v-model="pageParams.name" placeholder="任务名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="$route.meta.manage" @click="addOne">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" ref="multipleTable" :data="tableData" :max-height="tableH" :height="tableH" border>
      <el-table-column prop="jobName" label="任务名称" show-overflow-tooltip width="150"></el-table-column>
      <el-table-column prop="beanName" label="bean名称" show-overflow-tooltip width="100"></el-table-column>
      <el-table-column prop="methodName" label="方法名称" show-overflow-tooltip width="100"></el-table-column>
      <el-table-column prop="params" label="参数" show-overflow-tooltip width="100"></el-table-column>
      <el-table-column prop="cronExpression" label="表达式" show-overflow-tooltip width="140"></el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <div slot="reference" class="name-wrapper">
            <template v-if="scope.row.status == 1">
              <el-tag size="mini">执行中</el-tag>
            </template>
            <template v-else-if="scope.row.status == 0">
              <el-tag type="danger" size="mini">暂停</el-tag>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" :width="!$route.meta.manage ? '400' : '400'">
        <template slot-scope="scope">
          <el-button @click="updateOne(scope.row)" type="primary" size="mini">{{ $route.meta.manage ? '编辑' : '详情' }}</el-button>
          <el-popconfirm v-if="$route.meta.manage" title="确定删除吗？" @confirm="removeOne(scope.row.id)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
          <el-button @click="pauseJob(scope.row)" type="primary" size="mini">暂停</el-button>
          <el-button @click="resumeJob(scope.row)" type="primary" size="mini">恢复</el-button>
          <el-button @click="runJob(scope.row)" type="primary" size="mini">立即执行</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="pageParams.pageNo"
      background
      layout="total, prev, pager, next, jumper, sizes"
      :page-size="pageParams.pageSize"
      :total="total"
    ></el-pagination>
    <el-dialog
      top="5vh"
      width="40%"
      :close-on-click-modal="false"
      :title="!$route.meta.manage ? '详情' : form.id ? '编辑' : '添加'"
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
    >
      <el-form ref="form" :model="form" :disabled="!$route.meta.manage" :rules="formRules" label-width="110px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="任务名称" />
        </el-form-item>
        <el-form-item label="bean名称" prop="beanName">
          <el-input v-model="form.beanName" placeholder="bean名称" />
        </el-form-item>
        <el-form-item label="方法名称" prop="methodName">
          <el-input v-model="form.methodName" placeholder="方法名称" />
        </el-form-item>
        <el-form-item label="参数">
          <el-input v-model="form.params" />
        </el-form-item>
        <el-form-item label="表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="cron表达式" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button :loading="saving" type="primary" v-if="$route.meta.manage" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { deleteJob, getList, add, update, run, pause, resume } from '@/api/scheduleJob';
import { mapState } from 'vuex';
import { getStyle } from '@/utils/common';

const defaultProps = {
  id: null,
  jobName: '',
  beanName: '',
  methodName: '',
  params: '',
  cronExpression: '',
  status: null,
};

export default {
  name: 'ScheduleJob',
  data(props) {
    return {
      jobIds: [],
      edit: false,
      loading: false,
      saving: false,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        name: '',
      },
      form: props._.cloneDeep(defaultProps),
      dialogVisible: false,
      tableData: [],
      total: 0,
      formRules: {
        jobName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        beanName: [{ required: true, message: '请输入bean名称', trigger: 'blur' }],
        methodName: [{ required: true, message: '请输入方法名称', trigger: 'blur' }],
        cronExpression: [{ required: true, message: '请输入cron表达式', trigger: 'blur' }],
      },
    };
  },

  computed: {
    ...mapState('layout', ['tableHeight']),

    tableH() {
      if (this.tableHeight) {
        let html = getStyle(document.documentElement);
        let htmlFont = Number(html.fontSize.replace('px', ''));
        return this.tableHeight - 1.5 * htmlFont;
      }
      return null;
    },
  },
  methods: {
    handleSelectionChange(val) {
      this.jobIds = val;
    },
    pauseJob(row) {
      this.jobIds = [];
      this.jobIds.push(row.id);
      pause({
        jobIds: this.jobIds.join(','),
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success',
        });
      });
    },
    resumeJob(row) {
      this.jobIds = [];
      this.jobIds.push(row.id);
      resume({
        jobIds: this.jobIds.join(','),
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success',
        });
      });
    },
    runJob(row) {
      this.jobIds = [];
      this.jobIds.push(row.id);
      run({
        jobIds: this.jobIds.join(','),
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success',
        });
      });
    },
    addOne(row) {
      if (row) {
        this.form.name = row.name;
      }
      this.dialogVisible = true;
    },
    handleSearch() {
      this.loadData();
    },
    loadData() {
      this.loading = true;
      getList(this.pageParams)
        .then((res) => {
          if (res.data) {
            this.tableData = res.data;
            this.total = (res.additionalProperties.page && res.additionalProperties.page.total) || res.data.length;
          }
        })
        .finally(() => (this.loading = false));
    },
    handleCancel() {
      this.form = this._.cloneDeep(defaultProps);
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;

        this.saving = true;
        console.log({
          ...this.form,
        });
        debugger;
        if (this.form && this.form.id) {
          update({
            ...this.form,
          })
            .then(() => {
              this.$message({
                message: '保存成功',
                type: 'success',
              });
              this.loadData();
              this.handleCancel();
            })
            .finally(() => (this.saving = false));
        } else {
          add({
            ...this.form,
          })
            .then(() => {
              this.$message({
                message: '保存成功',
                type: 'success',
              });
              this.loadData();
              this.handleCancel();
            })
            .finally(() => (this.saving = false));
        }
      });
    },
    updateOne(row) {
      this.form = this._.pick(row, Object.keys(defaultProps));
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    removeOne() {
      deleteJob({}).then(() => {
        this.$message({
          message: '删除成功',
          type: 'success',
        });
        this.loadData();
      });
    },
    handleSizeChange(pageSize) {
      this.pageParams.pageSize = pageSize;
      this.loadData();
    },
    handleCurrentChange(pageNo) {
      this.pageParams.pageNo = pageNo;
      this.loadData();
    },
  },
  mounted() {
    this.loadData();
  },
};
</script>
